package com.common.library.ui.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.library.R;
import com.common.library.net.HttpException;
import com.common.library.net.HttpQueue;
import com.common.library.net.HttpResponse;
import com.common.library.tools.JSONTools;
import com.common.library.ui.view.adapter.base.BaseDrawRecyclerAdapter;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.yolanda.nohttp.error.NetworkError;
import com.yolanda.nohttp.error.TimeoutError;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Response;

import java.util.List;

/**
 * @author txf
 * @Title 拉伸头部的RecyclerFragment
 * @package com.txf.prevention.ui.fragment
 * @date 2017/5/5 0005
 */
public abstract class BaseDrawRecyclerFragment<T> extends BaseFragment implements OnResponseListener<String>, BaseDrawRecyclerAdapter.OnDrawTouchClick {
    private RelativeLayout mTitleLayout;
    private TextView mTitle;
    private TextView mSearch;

    private RecyclerView mRecyclerView;
    private BaseDrawRecyclerAdapter<T> mAdapter;
    private RecyclerView.ItemDecoration mItemDecoration;

    private int mColumnCount = 1;//列数
    protected LinearLayoutManager mManager;
    protected int pageIndex = 1;//页码
    protected int pageSize = 24;//每页条数
    protected long pageTime;// onResume 页面上次刷新时间
    protected long pageRefreshInterval = 60000000;// onResume 页面刷新间隔

    @Override
    protected View buildChildView() {
        return LayoutInflater.from(getContext()).inflate(R.layout.fragment_base_recycler2, null);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        initView(view);
        init();
    }

    private void initView(View view) {
        mTitleLayout = (RelativeLayout) view.findViewById(R.id.fragment_base_title_layout);
        mTitle = (TextView) view.findViewById(R.id.fragment_base_title);
        mSearch = (TextView) view.findViewById(R.id.fragment_base_search);

        mRecyclerView = (RecyclerView) view.findViewById(R.id.base_recycler_RecyclerView);
    }

    private void init() {
        mRecyclerView.setLayoutManager(mManager = new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);
        if (mItemDecoration != null)
            mRecyclerView.addItemDecoration(mItemDecoration);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (System.currentTimeMillis() - pageTime > pageRefreshInterval) {
            pageTime = System.currentTimeMillis();
            mRecyclerView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //自动刷新
                    request(pageIndex);
                }
            }, 100);
        }
    }

    protected abstract void request(int pageIndex);

    public void refreshData(List<T> datas) {
        if (pageIndex == 1) {
            if (datas != null)
                mAdapter.setDatas(datas);
        } else {
            if (datas != null)
                mAdapter.addDatas(datas);
        }
        if (datas != null)
            mAdapter.notifyDataSetChanged();
    }

    public void setAdapter(BaseDrawRecyclerAdapter<T> mAdapter) {
        this.mAdapter = mAdapter;
    }

    public void setItemDecoration(RecyclerView.ItemDecoration mItemDecoration) {
        this.mItemDecoration = mItemDecoration;
    }

    public void setColumnCount(int mColumnCount) {
        this.mColumnCount = mColumnCount;
    }

    public RecyclerView getmRecyclerView() {
        return mRecyclerView;
    }

    public TextView getmTitle() {
        return mTitle;
    }

    public RelativeLayout getmTitleLayout() {
        return mTitleLayout;
    }

    public LinearLayoutManager getmManager() {
        return mManager;
    }

    public TextView getmSearch() {
        return mSearch;
    }

    public void setTitle(String data) {
        mTitle.setText(data);
    }

    public int getManagerSpanSize(int position) {
        return 1;
    }

    public int dip2px(float dipValue) {
        float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    @Override
    public void onStop() {
        super.onStop();
        //页面关闭时，取消请求及相关动画
        HttpQueue.newHttpQueue().cancelRequest(TAG);
    }


    private View mDrawView;
    private DisplayMetrics metric;
    public float mFirstPosition;
    public boolean mScaling;

    @Override
    public void onDrawTouch(View view) {
        mDrawView = view;
        metric = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mDrawView.getLayoutParams();
        lp.width = metric.widthPixels;//头部itemView的宽度
        lp.height = dip2px(260);////头部itemView的高度
//        Logger.i("view 宽度 ; " + view.getWidth() + "\n" + "view 高度: " + view.getHeight());
//        Logger.i(" lp.width 宽度 ; " + lp.width + "\n" + "lp.height 高度: " + lp.height);
        mDrawView.setLayoutParams(lp);
        initzoomimage();
    }

    /**
     * 图片缩放的处理
     */
    private void initzoomimage() {
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mDrawView.getLayoutParams();
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mScaling = false;
                        replyDrawView();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (!mScaling) {
                            //当图片也就是第一个item完全可见的时候，记录触摸屏幕的位置
                            if (mManager.findViewByPosition(mManager.findFirstVisibleItemPosition()).getTop() == 0
                                    && mManager.findFirstVisibleItemPosition() == 0) {
                                mFirstPosition = event.getY();
                            } else {
                                break;
                            }
                        }
                        int distance = (int) ((event.getY() - mFirstPosition) * 0.6); // 滚动距离乘以一个系数
                        if (distance < 0) {
                            break;
                        }
                        // 处理放大
                        mScaling = true;
                        lp.width = metric.widthPixels + distance;
                        lp.height = dip2px(260) + distance;
                        mDrawView.setLayoutParams(lp);
                        return true;
                }
                return false;
            }
        });
    }
    /**
     * 重置DrawView大小
     */
    private void replyDrawView() {
        final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mDrawView.getLayoutParams();
        final float w = mDrawView.getLayoutParams().width;// mDrawView当前宽度
        final float h = mDrawView.getLayoutParams().height;// mDrawView当前高度
        final float newW = metric.widthPixels;// mDrawView原宽度
        final float newH = dip2px(260);// mDrawView原高度
        // 设置动画
        ValueAnimator anim = ObjectAnimator.ofFloat(0.0F, 1.0F).setDuration(200);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float cVal = (Float) animation.getAnimatedValue();
                lp.width = (int) (w - (w - newW) * cVal);
                lp.height = (int) (h - (h - newH) * cVal);
                mDrawView.setLayoutParams(lp);
            }
        });
        anim.start();
    }
    /////////////////////////////////////////////////////////////////////
    //////////////////////////////网络请求回执///////////////////////////
    /////////////////////////////////////////////////////////////////////
    @Override
    public void onStart(int what) {
    }

    @Deprecated
    @Override
    public void onSucceed(int what, Response<String> response) {
        Log.i(TAG, "--->UN 请求结果数据:");
        Log.i(TAG, response.get().toString());
        String strDecode = response.get().toString();
        HttpResponse result = JSONTools.fromJson(strDecode, HttpResponse.class);
        //无效数据过滤掉。
        if (result == null) {
            onError(what, HttpException.NONE_RESULT.getCode(), HttpException.NONE_RESULT.getMessage());
            return;
        }
        //服务器返回的错误信息在2000以后
        int error = Integer.parseInt(result.getErrCode());
        if (error != 0) {
            onError(what, error, result.getMsg());
            return;
        }
        onSuccess(what, new JsonParser().parse(strDecode), result.getMsg());
    }

    /**
     * 错误响应时
     *
     * @param what     多个请求时。该字段用于区别
     * @param response failure callback.
     */
    @Deprecated
    @Override
    public void onFailed(int what, Response<String> response) {
        response.getException().printStackTrace();
        if (response.getException() instanceof TimeoutError) {
            onError(what, HttpException.DEFAULT.getCode(), "请求超时");
        } else if (response.getException() instanceof NetworkError) {
            onError(what, HttpException.DEFAULT.getCode(), "网络异常");
        } else {
            onError(what, HttpException.DEFAULT.getCode(), HttpException.NONE_RESULT.getMessage());
        }
    }

    public void onSuccess(int what, JsonElement data, String message) {
    }

    public void onError(int what, int error, String message) {
    }

    @Override
    public void onFinish(int what) {
    }
}
